import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as express from 'express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './core/filter/any-exception.filter';
import { HttpExceptionFilter } from './core/filter/http-exception';
import { TransformInterceptor } from './core/interceptor/transform.interceptor';
import { logger } from './middleware/logger.middleware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(express.json()); // For parsing application/json
  app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded

  app.setGlobalPrefix('api'); // 设置全局路由前缀
  app.useGlobalFilters(new AllExceptionsFilter()); // 要在 HttpExceptionFilter 的上面，否则 HttpExceptionFilter 就不生效了，全被 AllExceptionsFilter 捕获了
  app.useGlobalFilters(new HttpExceptionFilter()); // 注册全局错误的过滤器
  app.useGlobalInterceptors(new TransformInterceptor()); // 全局注册拦截器
  app.useGlobalPipes(new ValidationPipe()); // 注册全局管道
  app.use(logger); // 日志中间件

  //  访问地址 http://127.0.0.1:3000/docs
  const config = new DocumentBuilder()
    .setTitle('个人项目')
    .setDescription('个人项目结构文档')
    .addBearerAuth()
    .setVersion('1.0.0')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('docs', app, document);

  await app.listen(3000);
}
bootstrap();
